package UILayer;

import java.util.ArrayList;
import java.util.Scanner;

/**
 * The MenuList class keeps information about the contents of a menu. 
 * It allows the program to display menus in a consistent way, it ensures that only valid choices are
 * made by the user.
 * A MenuList object contains the options to be displayed in the menu it represents. 
 * The MenuList class is responsible to create Options.
 * The generic type argument defines the type of the objects that are represented by the options 
 * displayed in the menu.This is also the type that the MenuList object returns when the user chooses
 * an option.
 * 
 * @author anna
 *
 */
public class MenuList <T> {
	private String text;
    private String prompt;
    private ArrayList <Option<T>> options;
    private boolean found;
	
	/**
	 * Constructor for Menu List objects.
	 * 
	 * @param text Description to be displayed in the menu.
	 * @param prompt Prompt text for the user to be displayed in the menu.
	 */
    public MenuList(String text, String prompt) {
		this.text = text;
		this.prompt = prompt;
		options = new ArrayList<Option<T>>();
	}
    
    /**
     * Creates new Option objects and adds them to the MenuList.
     * 
     * @param choice  The number or symbol of an option.
     * @param text Description of an option.
     * @param choiceObj
     */
    public void addOption(String choice, String text, T choiceObj){
    	Option <T> option = new Option<T>(choice, text, choiceObj); 
    	options.add(option);
    }
    
    /**
     * Displays a list of options, reads the users input and returns an object, whose option equals
     * with the users input.
     * 
     * @return T An object of generic type argument. 
     */
    public T display(){
        T result = null;
        found = false;
        do {
            System.out.println(text);
            for (int i = 0; i < options.size(); i++){
                Option<T> o = options.get(i);
                System.out.println(" " + o.getChoice() + "\t" + o.getText());
            }
            System.out.print(prompt);
            String input = new Scanner(System.in).nextLine();
            result = findChoice(input);
        }
        while (!found);
        return result;
    }
    /**
     * A helper method which returns an Option object from the list found by the users input.
     * 
     * @return T An object of generic type argument. 
     */
    private T findChoice(String input){
        for (Option<T> o : options){
            if (o.getChoice().equals(input)){
                found = true;
                return o.getChoiceObj();
            }
        }
        return null;
    }
}
